package hr.fer.zesoi.neumre;

import hr.fer.zesoi.neumre.logic.TetrisBoard;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JComponent;

public class TetrisBoardComponent extends JComponent {

	private static final long serialVersionUID = 7801244030176715026L;

	private TetrisBoard board;

	private int pixelWidth;

	private int pixelHeight;

	private int colSpacing;

	private int rowSpacing;

	public TetrisBoardComponent(TetrisBoard board) {

		this.board = board;
		this.board.registerComponent(this);
	}

	public void boardChanged() {

		this.repaint();
	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponents(g);
		
		g.setColor(Color.gray);
		g.fillRect(0, 0, this.getSize().width, this.getSize().height);

		this.pixelWidth = (int) Math.floor(this.getSize().width
				/ board.getCols());
		this.pixelHeight = (int) Math.floor(this.getSize().height
				/ board.getRows());

		this.colSpacing = Math.max(1, pixelWidth / 25);
		this.rowSpacing = Math.max(1, pixelHeight / 25);

		for (int row = 0; row < board.getRows(); row++)
			for (int col = 0; col < board.getCols(); col++) {
				int value = board.getPixelValue(row, col);

				if (value != 0) {
					if (value == 1) {
						g.setColor(Color.black);
					} else {
						g.setColor(Color.red);
					}

					drawPixel(row, col, g);
				}
			}
	}

	private void drawPixel(int row, int col, Graphics g) {

		int posX = col * pixelWidth;
		int posY = this.getSize().height - (row + 1) * pixelHeight;

		g.fillRect(posX + colSpacing, posY + rowSpacing, pixelWidth - 2
				* colSpacing, pixelHeight - 2 * rowSpacing);
	}
}
